package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService bookService;

    /**
     * 添加收货地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R add(@RequestBody AddressBook addressBook){
        System.out.println("addressBook = " + addressBook);
        int row = bookService.add(addressBook);
        if (row>0) return R.success("保存成功");
        return R.error("保存失败");
    }

    /**
     * 查询所有收货地址
     * @return
     */
    @GetMapping("/list")
    public R findAll(){

        try {
            return R.success(bookService.findAll());
        }catch (Exception e){
            e.printStackTrace();
            return R.error("查询失败");
        }

    }

    /**
     * 更新收货地址以及设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook){
        System.out.println("addressBook = " + addressBook);
        int row = bookService.update(addressBook);
        if (row>0) return R.success("修改成功");
        return R.error("修改失败");
    }

    //删除地址
    @DeleteMapping
    public R deleteById(Long ids){
        int row = bookService.deleteById(ids);
        if (row>0) return R.success("删除成功");
        return R.error("删除失败");
    }

// 获得默认地址接口 /addressBook/default
    @GetMapping("/default")
    public R getdefault(HttpSession httpSession){
        User user = (User)httpSession.getAttribute("user");
        AddressBook addressBook=bookService.getdefault(user.getId());
        return R.success(addressBook);
    }
}
